# -*- coding:utf-8 -*—
import os

import pandas as pd
import docx

from docx.shared import Inches

from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def readExcel(excelPath):
    df = pd.read_excel(io=excelPath)
    return df


def file_name(file_path):
    """
    获取每个文件的路径
    root 为当前目录路径
    dirs 为当前路径下所有子目录
    files 为当前路径下所有非目录子文件
    :param file_path:
    :return:
    """
    paths_list = []
    for root,dirs,files in os.walk(file_path):
        for file in files:
            path_list = os.path.join(root,file)
            paths_list.append(path_list)
    return paths_list

#设置表格的边框
def set_cell_border(cell, **kwargs):
    """
    Set cell`s border
    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        left={"sz": 24, "val": "dashed", "shadow": "true"},
        right={"sz": 12, "val": "dashed"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    # list over all available tags
    for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))
def setStyle(cell):
    # set_cell_border(
    #     cell,
    #     top={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"},
    #     bottom={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"},
    #     left={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"},
    #     right={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"},
    #     insideH={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"},
    #     end={"sz": 0.5, "val": "double", "color": "#000000", "space": "0"}
    # )
    set_cell_border(
        cell,
        top={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"},
        bottom={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"},
        left={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"},
        right={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"},
        insideH={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"},
        end={"sz": 0.5, "val": "single", "color": "#000000", "space": "0"}
    )

def excelList2word(excelDir, wordPath):

    path_lists = file_name(excelDir)
    doc = docx.Document(wordPath)

    list_data = []
    for path in path_lists:
        try:
            df = readExcel(path)
            filename = os.path.basename(path)
            stem, suffix = os.path.splitext(filename)
            print(stem)
            print(suffix)
            # todo：添加标题行
            paragraph = doc.add_paragraph(stem)

            table = doc.add_table(df.shape[0] + 1, df.shape[1])

            # add the header rows.
            for j in range(df.shape[-1]):
                table.cell(0, j).text = df.columns[j]
                setStyle(table.cell(0, j))
            # add the rest of the data frame
            for i in range(df.shape[0]):
                for j in range(df.shape[-1]):
                    table.cell(i + 1, j).text = str(df.values[i, j])
                    setStyle(table.cell(i + 1, j))

            doc.add_page_break()
        except Exception as e:
            print("读取错误:", e)
    # save the doc
    doc.save(wordPath)


def excel2word(excelPath,wordPath):
    # i am not sure how you are getting your data, but you said it is a
    # pandas data frame
    df = readExcel(excelPath)

    # open an existing document
    # doc = docx.Document('./test.docx')
    doc = docx.Document(wordPath)

    # add a table to the end and create a reference variable
    # extra row is so we can add the header row
    t = doc.add_table(df.shape[0]+1, df.shape[1])

    # add the header rows.
    for j in range(df.shape[-1]):
        t.cell(0,j).text = df.columns[j]

    # add the rest of the data frame
    for i in range(df.shape[0]):
        for j in range(df.shape[-1]):
            t.cell(i+1,j).text = str(df.values[i,j])

    doc.add_page_break()

    # save the doc
    doc.save(wordPath)

if __name__ == '__main__':
    # wordPath=r"F:\test.docx"
    #
    # excelPath=r"G:\1.项目相关_不删\400.安徽柏堰APP\2.APP表结构\数据库表结构\appworker.xlsx"
    # excel2word(excelPath,wordPath)

    wordPath = r"F:\test2.docx"

    excelPath = r"G:\1.项目相关_不删\400.安徽柏堰APP\2.APP表结构\数据库表结构"
    excelList2word(excelPath, wordPath)
    print("------完成-------")
